
<template>
  <BasicLayout>
    <template #wrapper>
      <el-card class="box-card" style="padding: 36px">
        <el-steps :active="active" finish-status="success" simple>
          <el-step title="课程信息" />
          <el-step title="其他信息" />
        </el-steps>
        <div style="padding: 36px">
          <el-form v-show="active === 0" ref="courseForm" :model="courseForm" :rules="rules" label-width="80px">
            <el-form-item label="课程名称" prop="name">
              <el-input v-model="courseForm.name" placeholder="请输入课程名称" style="width: 40%" />
            </el-form-item>
            <el-form-item label="适用地区" prop="province">
              <el-select
                v-model="courseForm.province"
                remote
                filterable
                placeholder="请选择地区"
                :remote-method="remoteMethod"
                :loading="selectload"
                style="width: 40%"
                @change="selectRegion"
              >
                <el-option v-for="(item, index) in cityList" :key="index" :label="item.name" :value="item.name" />
              </el-select>
            </el-form-item>
            <el-form-item label="课程科目" prop="subject">
              <el-select v-model="courseForm.subject" filterable placeholder="请选择科目" style="width: 40%">
                <el-option v-for="(item, index) in subjectList" :key="index" :label="item.name" :value="item.name" />
              </el-select>
            </el-form-item>
            <el-form-item label="课程封面" prop="cover">
              <el-upload
                :headers="headers"
                class="avatar-uploader"
                :action="host + '/api/v1/public/uploadFile'"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="courseForm.cover" :src="getMediaUrl(courseForm.cover)" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon" />
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2M</div>
              </el-upload>
            </el-form-item>
            <el-form-item label="课程状态" prop="status">
              <el-switch
                v-model="courseForm.status"
                :active-value="1"
                :inactive-value="-1"
                active-text="上架"
                inactive-text="下架"
              />
            </el-form-item>
            <el-form-item label="课程价格" prop="price">
              <el-input-number v-model="courseForm.price" controls-position="right" placeholder="请输入课程价格" />
            </el-form-item>
            <el-form-item label="课程描述" prop="introduction">
              <el-row :gutter="3" style="margin-left: 0">
                <el-col
                  v-for="(item, index) in courseForm.introduction"
                  :key="index"
                  style="margin-bottom: 10px"
                  :span="6"
                >
                  <Pictures :url="getMediaUrl(item)" :index="index" @deletefile="handleRemove" />
                </el-col>
                <el-col :span="6">
                  <el-upload
                    :headers="headers"
                    class="avatar-uploader"
                    :action="host + '/api/v1/public/uploadFile'"
                    :show-file-list="false"
                    :on-success="handleAvatarOutline"
                    :before-upload="beforeAvatarUpload"
                  >
                    <i class="el-icon-plus avatar-uploader-icon" />
                    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2M</div>
                  </el-upload>
                </el-col>
              </el-row>
            </el-form-item>
            <!-- <el-form-item label="课程描述" prop="introduction">
              <el-input v-model="courseForm.introduction" type="textarea" placeholder="请输入内容" :rows="2"
                style="width: 40%" />
            </el-form-item> -->
            <el-form-item label="试听课程" prop="audition_link">
              <div v-if="courseForm.audition_link">
                <span style="cursor:pointer" @click="() => playVideo(courseForm.audition_link)">{{
                  courseForm.audition_course_name
                }}</span>
                <i
                  class="el-icon-delete"
                  style="margin-left: 10px;cursor:pointer"
                  @click="(event) => beforeRemove(event, courseForm.audition_course_name)"
                />
              </div>
              <el-progress
                v-else-if="loading"
                :text-inside="true"
                :stroke-width="15"
                :percentage="percentage"
                style="width: 40%"
              />
              <el-upload
                v-else
                :headers="headers"
                class="upload-demo"
                style="width: 40%"
                action
                :http-request="httpUpload"
                :show-file-list="false"
              >
                <div v-if="!loading">
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">只能上传mp4/wav文件</div>
                </div>
              </el-upload>
            </el-form-item>
          </el-form>

          <el-form
            v-show="active === 1"
            ref="lecturerForm"
            :model="lecturerForm"
            :rules="rules"
            label-position="right"
            label-width="106px"
          >
            <el-form-item label="教师介绍" prop="lecturer_id">
              <el-select v-model="lecturerForm.lecturer_id" filterable placeholder="请选择教师" style="width: 40%">
                <el-option v-for="item in teacherList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="直播日期" prop="start_time">
              <el-date-picker
                v-model="lecturerForm.start_time"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 40%"
              />
            </el-form-item>
            <el-form-item label="直播地址" prop="live_url">
              <el-input v-model="lecturerForm.live_url" placeholder="请输入直播地址" style="width: 40%" />
            </el-form-item>
          </el-form>

          <div style="float:right">
            <el-button v-show="active !== 0" style="margin-top: 12px;" @click="lastStep">上一步</el-button>
            <el-button type="primary" style="margin-top: 12px;" @click="submitForm">{{ active === 1 ? '确认' : '下一步' }}
            </el-button>
          </div>
        </div>
      </el-card>
      <Video :show-video="showVideo" :play-url="playUrl" @handleHideModal="handleHideModal" />
    </template>
  </BasicLayout>
</template>

<script>
import {
  getCity,
  addCourse,
  editCourse,
  getSubject,
  getDetails
} from '@/api/admin/sys-course'
import { getToken } from '@/utils/auth'
import { getLeacher } from '@/api/admin/sys-teacher'
import { clients, getNowDate } from '@/utils/index'
import Video from '@/components/Video'
import Pictures from '@/components/Pictures'
export default {
  components: {
    Video,
    Pictures
  },
  data() {
    return {
      headers: { Authorization: 'Bearer ' + getToken() },
      host: '',
      active: 0,
      flagchange: 0,
      lecturerchange: 0,
      isChange: false,
      courseForm: {
        cover: null,
        status: -1,
        subject: null,
        introduction: []
      },
      lecturerForm: {
        course_type: 'live'
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: '课程名称不能为空', trigger: 'blur' }
        ],
        subject: [
          { required: true, message: '课程科目不能为空', trigger: 'blur' }
        ],
        cover: [{ required: true, message: '上传课程封面', trigger: 'blur' }],
        status: [{ required: true, message: '选择课程状态', trigger: 'blur' }],
        price: [
          { required: true, message: '课程价格不能为空', trigger: 'blur' }
        ],
        introduction: [
          { required: true, message: '课程简介不能为空', trigger: 'blur' }
        ],
        lecturer_id: [{ required: true, message: '选择教师', trigger: 'blur' }],
        province: [
          { required: true, message: '选择适用地区', trigger: 'blur' }
        ],
        start_time: [
          { required: true, message: '日期不能为空', trigger: 'blur' }
        ],
        live_url: [
          { required: true, message: '直播地址不能为空', trigger: 'blur' }
        ]
      },
      cityList: [],
      teacherList: [],
      courseId: null,
      subjectList: [],
      selectload: false,
      loading: false,
      showVideo: false,
      playUrl: '',
      percentage: 0
    }
  },
  watch: {
    courseForm: {
      deep: true,
      handler(val) {
        this.flagchange++
        if (this.flagchange > 2) {
          // 说明监听值有变化
          this.isChange = true // 弹框提示
        }
        if (val.province) {
          getSubject({ province: val.province }).then(res => {
            this.subjectList = res?.data || []
          })
        }
      }
    },
    lecturerForm: {
      deep: true,
      handler(val) {
        this.lecturerchange++
        if (this.lecturerchange > 1) {
          // 说明监听值有变化
          this.isChange = true // 弹框提示
        }
      }
    }
  },
  created() {
    this.host = process.env.VUE_APP_BASE_API
    getLeacher().then(res => {
      this.teacherList = res?.data || []
    })
    getCity().then(res => {
      this.cityList = res?.data || []
    })
    if (this.$route.params.id) {
      /** 获取课程详情 */
      this.courseId = this.$route.params && Number(this.$route.params.id)
      getDetails(this.courseId).then(response => {
        const { data = {}} = response
        const courseInfor = {
          ...data?.step1,
          introduction: data?.step1?.introduction?.includes('://')
            ? data?.step1?.introduction.split(',')
            : []
        }
        this.courseForm = {
          ...courseInfor,
          price: courseInfor.price / 100
        }
        this.lecturerForm = {
          ...data?.step2,
          start_time: [data?.step2.start_time, data?.step2.end_time]
        }
      })
    }
  },
  methods: {
    selectRegion(val) {
      this.courseForm.subject = null
      getSubject({ province: val }).then(res => {
        this.subjectList = res?.data || []
      })
    },
    traverseRender(data) {
      return data?.map(item => {
        return {
          key: item.id,
          value: item.id,
          label: item.label,
          children:
            item.children.length > 0 ? this.traverseRender(item.children) : null
        }
      })
    },

    // 上一步
    lastStep() {
      if (this.active-- < 1) return (this.active = 0)
    },
    // 下一步
    submitForm() {
      if (this.active === 0) {
        this.$refs['courseForm'].validate(courseValid => {
          if (courseValid) {
            this.active++
          } else {
            return
          }
        })
      } else if (this.active === 1) {
        this.$refs['lecturerForm'].validate(lecturerValid => {
          if (lecturerValid) {
            const payload = {
              step1: {
                ...this.courseForm,
                price: this.courseForm.price * 100,
                introduction: this.courseForm.introduction.toString()
              },
              step2: {
                ...this.lecturerForm,
                start_time: this.lecturerForm.start_time[0],
                end_time: this.lecturerForm.start_time[1]
              }
            }
            if (this.$route.params.id && this.isChange) {
              editCourse({
                ...payload,
                course_id: this.courseId
              }).then(res => {
                if (res.code === 200) {
                  this.msgSuccess(res.msg)
                  this.$router.push('/admin/sys-course/live')
                } else {
                  this.msgError(res.msg)
                }
              })
            } else if (this.$route.params.id) {
              this.$router.push('/admin/sys-course/live')
            } else {
              addCourse(payload).then(res => {
                if (res.code === 200) {
                  this.msgSuccess(res.msg)
                  this.$router.push('/admin/sys-course/live')
                } else {
                  this.msgError(res.msg)
                }
              })
            }
          }
        })
      }
    },

    handleRemove(file) {
      this.courseForm.introduction = this.courseForm.introduction.filter(
        (item, index) => file !== index
      )
    },
    handleAvatarOutline(res) {
      this.courseForm.introduction.push(res.data.full_path)
    },
    handleAvatarSuccess(res) {
      this.courseForm.cover = res.data.full_path
    },
    
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2.0
      const isJPG = file.type.indexOf('image/') === -1
      if (isJPG) {
        this.$message.error(
          '文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件'
        )
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2M!')
      }
      return !isJPG && isLt2M
    },
    remoteMethod(query) {
      if (query !== '') {
        this.selectload = true
        getCity({ name: query }).then(res => {
          this.cityList = res?.data || []
          this.selectload = false
        })
      } else {
        this.cityList = []
      }
    },
    playVideo(url) {
      this.showVideo = true
      this.playUrl = url
    },
    handleHideModal() {
      this.playUrl = ''
      this.showVideo = false
    },
    beforeRemove(event, file) {
      event.stopPropagation()
      return this.$confirm(`确定移除 ${file}？`)
        .then(() => {
          this.courseForm.audition_link = ''
          this.courseForm.audition_course_name = ''
          this.percentage = 0
        })
        .catch(() => { })
    },
    async httpUpload(file) {
      try {
        // 判断扩展名
        const tmpcnt = file.file.name.lastIndexOf('.')
        const exname = file.file.name.substring(tmpcnt + 1)
        const client = clients()
        const names = ['wav', 'mp4']
        if (names.indexOf(exname) < 0) {
          this.$message.error('不支持的格式!')
          return
        }
        this.loading = true
        const imgUrl = 'http://image.twzxjy.com'
        const fileName = `static/uploadfile/${getNowDate()}/${file.file.uid
        }.${exname}`
        // 依次填写Object完整路径（例如exampledir/exampleobject.txt）和本地文件的完整路径（例如D:\\localpath\\examplefile.txt）。Object完整路径中不能包含Bucket名称。
        // 如果本地文件的完整路径中未指定本地路径（例如examplefile.txt），则默认从示例程序所属项目对应本地路径中上传文件。
        await client.multipartUpload(fileName, file.file, {
          progress: (p, cpt, res) => {
            // 获取分片上传进度、断点和返回值。
            this.percentage = (Math.floor(p * 100) / 100) * 100
            if (p === 1) {
              this.loading = false
            }
          },
          parallel: 5, // 并发上传的分片数量
          partSize: 1024 * 1024 * 20,
          // headers,
          // 指定meta参数，自定义Object的元信息。通过head接口可以获取到Object的meta数据。
          meta: {
            year: 2020,
            people: 'test'
          },
          mime: file.type // 上传文件类型
        })
        // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        const head = await client.head(fileName)
        if (head.status === 200) {
          this.$set(this.courseForm, 'audition_link', `${imgUrl}/${fileName}`)
          this.$set(this.courseForm, 'audition_course_name', file.file.name)
        }
      } catch (e) {
        if (e.code === 'ConnectionTimeoutError') {
          console.log('TimeoutError')
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

::v-deep .el-form-item__content {
  .el-progress {
    line-height: 2.3;
  }
}
</style>
